package com.aiprompt.demos.controller;

import com.aiprompt.demos.model.dto.user.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.aiprompt.demos.anotation.AuthCheck;
import com.aiprompt.demos.common.BaseResponse;
import com.aiprompt.demos.common.DeleteRequest;
import com.aiprompt.demos.common.ResultUtils;
import com.aiprompt.demos.constant.UserConstant;
import com.aiprompt.demos.exception.BusinessException;
import com.aiprompt.demos.exception.ErrorCode;
import com.aiprompt.demos.exception.ThrowUtils;
import com.aiprompt.demos.model.domain.User;
import com.aiprompt.demos.model.vo.user.LoginUserVO;
import com.aiprompt.demos.model.vo.user.UserVO;
import com.aiprompt.demos.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String userName = userRegisterRequest.getUserName();
        String email = userRegisterRequest.getEmail();
        String phone = userRegisterRequest.getPhone();
        Integer gender = userRegisterRequest.getGender();
        String registerSource = userRegisterRequest.getRegisterSource();

        long result = userService.userRegisterFull(userAccount, userPassword, checkPassword,
                                                  userName, email, phone, gender, registerSource);
        return ResultUtils.success(result);
    }
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }

    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    /**
     * 创建用户
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        final String DEFAULT_PASSWORD = "12345678";

        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        if(user.getUserPassword() != null) {
            encryptPassword = userService.getEncryptPassword(user.getUserPassword());
        }

        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        ThrowUtils.throwIf(userUpdateRequest == null || userUpdateRequest.getId() == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     *
     * @param userQueryRequest 查询请求参数
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {

        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();

        System.out.println(current+" "+pageSize);
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));


        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);


        return ResultUtils.success(userVOPage);
    }

    /**
     * 更新用户个人信息
     */
    @PostMapping("/update/profile")
    public BaseResponse<Boolean> updateUserProfile(@RequestBody UserUpdateProfileRequest request,
                                                  HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);

        User loginUser = userService.getLoginUser(httpRequest);
        Long userId = loginUser.getId();

        boolean result = userService.updateUserProfile(
            userId,
            request.getUserName(),
            request.getUserAvatar(),
            request.getUserProfile(),
            request.getEmail(),
            request.getPhone(),
            request.getGender(),
            request.getBirthday()
        );

        return ResultUtils.success(result);
    }

    /**
     * 修改用户密码
     */
    @PostMapping("/change/password")
    public BaseResponse<Boolean> changePassword(@RequestBody UserChangePasswordRequest request,
                                              HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);

        String oldPassword = request.getOldPassword();
        String newPassword = request.getNewPassword();
        String confirmPassword = request.getConfirmPassword();

        // 验证新密码和确认密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码和确认密码不一致");
        }

        User loginUser = userService.getLoginUser(httpRequest);
        Long userId = loginUser.getId();

        boolean result = userService.changePassword(userId, oldPassword, newPassword);

        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    public BaseResponse<LoginUserVO> getCurrentUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        LoginUserVO loginUserVO = userService.getLoginUserVO(loginUser);
        return ResultUtils.success(loginUserVO);
    }

    @GetMapping("/test-db")
    public BaseResponse<List<User>> testDb() {
        List<User> users = userService.list(); // 无条件查询所有用户
        System.out.println("Total users in DB: " + users.size());
        return ResultUtils.success(users);
    }

    @GetMapping("/generate-password")
    public BaseResponse<String> generatePassword() {
        org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder encoder =
            new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder();

        String admin123 = encoder.encode("admin123");
        String user123456 = encoder.encode("user123456");

        String result = "admin123 -> " + admin123 + "\n" +
                       "user123456 -> " + user123456;

        return ResultUtils.success(result);
    }

    @PostMapping("/init-users")
    public BaseResponse<String> initUsers() {
        try {
            // 清空现有用户
            userService.remove(null);

            org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder encoder =
                new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder();

            // 创建管理员用户
            User admin = new User();
            admin.setUserAccount("admin");
            String adminPassword = encoder.encode("admin123");
            admin.setUserPassword(adminPassword);
            admin.setUserName("系统管理员");
            admin.setUserRole("admin");
            admin.setEmail("admin@promptcraft.com");
            admin.setPhone("13800138000");
            admin.setGender(1);
            admin.setRegisterSource("system");
            admin.setStatus(1);
            userService.save(admin);

            // 创建测试用户
            User testUser = new User();
            testUser.setUserAccount("testuser");
            String userPassword = encoder.encode("user123456");
            testUser.setUserPassword(userPassword);
            testUser.setUserName("测试用户");
            testUser.setUserRole("user");
            testUser.setEmail("test@example.com");
            testUser.setPhone("13900139000");
            testUser.setGender(1);
            testUser.setRegisterSource("web");
            testUser.setStatus(1);
            userService.save(testUser);

            // 验证密码是否正确
            boolean adminCheck = encoder.matches("admin123", adminPassword);
            boolean userCheck = encoder.matches("user123456", userPassword);

            String result = String.format("用户初始化成功！\n管理员: admin/admin123 (密码验证: %s)\n测试用户: testuser/user123456 (密码验证: %s)",
                adminCheck ? "✓" : "✗", userCheck ? "✓" : "✗");

            return ResultUtils.success(result);
        } catch (Exception e) {
            return new BaseResponse<>(ErrorCode.SYSTEM_ERROR.getCode(), null, "初始化失败: " + e.getMessage());
        }
    }

    @PostMapping("/fix-admin-password")
    public BaseResponse<String> fixAdminPassword() {
        try {
            // 查找管理员用户
            User admin = userService.getOne(new QueryWrapper<User>().eq("userAccount", "admin"));
            if (admin == null) {
                return new BaseResponse<>(ErrorCode.NOT_FOUND_ERROR.getCode(), null, "管理员用户不存在");
            }

            // 使用明文密码 admin123
            admin.setUserPassword("admin123");
            userService.updateById(admin);

            return ResultUtils.success("管理员密码已重置为明文：admin123");
        } catch (Exception e) {
            return new BaseResponse<>(ErrorCode.SYSTEM_ERROR.getCode(), null, "密码重置失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户统计数据
     */
    @GetMapping("/stats")
    public BaseResponse<Object> getUserStats() {
        try {
            // 获取总用户数
            long totalUsers = userService.count();

            // 获取今日新增用户数
            QueryWrapper<User> todayWrapper = new QueryWrapper<>();
            todayWrapper.ge("createTime", java.time.LocalDate.now().atStartOfDay());
            long todayUsers = userService.count(todayWrapper);

            // 获取本月新增用户数
            QueryWrapper<User> monthWrapper = new QueryWrapper<>();
            monthWrapper.ge("createTime", java.time.LocalDate.now().withDayOfMonth(1).atStartOfDay());
            long monthUsers = userService.count(monthWrapper);

            // 构建统计数据
            java.util.Map<String, Object> stats = new java.util.HashMap<>();
            stats.put("totalUsers", totalUsers);
            stats.put("todayUsers", todayUsers);
            stats.put("monthUsers", monthUsers);

            return ResultUtils.success(stats);
        } catch (Exception e) {
            return new BaseResponse<>(ErrorCode.SYSTEM_ERROR.getCode(), null, "获取统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取最近注册的用户
     */
    @GetMapping("/recent")
    public BaseResponse<List<UserVO>> getRecentUsers(@RequestParam(defaultValue = "10") int limit) {
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("createTime");
            queryWrapper.last("LIMIT " + limit);

            List<User> users = userService.list(queryWrapper);
            List<UserVO> userVOList = users.stream()
                    .map(user -> {
                        UserVO userVO = new UserVO();
                        BeanUtils.copyProperties(user, userVO);
                        return userVO;
                    })
                    .collect(java.util.stream.Collectors.toList());

            return ResultUtils.success(userVOList);
        } catch (Exception e) {
            return new BaseResponse<>(ErrorCode.SYSTEM_ERROR.getCode(), null, "获取最近用户失败: " + e.getMessage());
        }
    }

}
